<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckCategory;
use think\exception\ValidateException;

// mall商城分类
class Category extends BaseController
{
    public function index()
    {
        return View::fetch();
    }




    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $total = Db::name('elearning_category')
            ->where('type', '=', 1)
            ->count();

        $rows = Db::name('elearning_category')
            ->where('type', '=', 1)
            ->order('sort', 'asc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $v['course_total'] = Db::name('elearning_course')->where('category_id', '=', $v['id'])->count();
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        return View::fetch();
    }

    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCategory::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $data = array(
                'name'      => $post['name'],
                'e_name'    => $post['e_name'],
                'icon'      => $post['icon'],
                'icon_pc'      => $post['icon_pc'],
                'icon_pc_on'      => $post['icon_pc_on'],
                'add_time'  => time(),
            );
            if (!Db::name('elearning_category')->insert($data)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
     * 修改
     */
    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        $id = $request->param('id');
        $inf = Db::name('elearning_category')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }



    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCategory::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $update = array(
                'id'        => $post['id'],
                'name'      => $post['name'],
                'e_name'    => $post['e_name'],
                'icon'      => $post['icon'],
                'icon_pc'      => $post['icon_pc'],
                'icon_pc_on'      => $post['icon_pc_on'],
                'add_time'  => time(),
            );
            if (!Db::name('elearning_category')->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function showIcon()
    {
        $type = input('type');
        View::assign('type',$type);
        return View::fetch();
    }

    public function getIconList()
    {
        $arr = array(
            array(
                'name' => '科技',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/1.png'
            ),
            array(
                'name' => '能效提升',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/2.png'
            ),
            array(
                'name' => '欧家文化',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/3.png'
            ),
            array(
                'name' => '数字化',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/4.png'
            ),
            array(
                'name' => '销售',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/5.png'
            ),
            array(
                'name' => '研发',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/6.png'
            ),
            array(
                'name' => '营销',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/7.png'
            ),
            array(
                'name' => '影响力',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/8.png'
            ),
            array(
                'name' => '最新',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/9.png'
            ),
            array(
                'name' => '更多',
                'url' => 'https://learningspark-resource.lorealchina.com/static/category_icon/10.png'
            ),
        );

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $arr
        );
        return json($data);
    }


    //+删除分类
    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        Db::startTrans();
        try {
            if (!Db::name('elearning_category')->where('id', '=', $id)->delete()) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]！');
            }
            $course = Db::name('elearning_course')->where('category_id', '=', $id)->select()->toArray();
            if (!empty($course)) {
                if (!Db::name('elearning_course')->where('category_id', '=', $id)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[2]！');
                }
            }
            Db::commit();
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
     * 排序
     * date: 2019-04-10
     * author: admin
     */
    public function sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        Db::startTrans();
        try {

            $res = Db::name('elearning_category')->where(array('id'=>$post['id']))->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('elearning_category')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort', 'asc')
                ->select();

            if (!Db::name('elearning_category')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('elearning_category')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function course(Request $request)
    {
        $id = $request->param('id');
        View::assign('id',$id);
        return View::fetch();
    }

    public function getCourseList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $category_id = $request->get('category_id');
        $get = $request->get();
        $where = [];
        $where[] = ['category_id', '=', $category_id];


        $total = Db::name('elearning_course')
            ->where($where)
            ->count();

        $rows = Db::name('elearning_course')
            ->where($where)
            ->order("sort", 'asc')
            ->field('sort, id as aid, type as course_type, courseid, category_id')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            if ($v['course_type'] == 'qxt') {
                $course_info = Db::name('qxt_courses')->where('id', '=', $v['courseid'])->field('courseTitle,category')->find();
                $v['seminar'] = $course_info['courseTitle'];
                $v['seminar_topic'] = $course_info['category'];
                $v['course_type_name'] = '轻学堂';

            } elseif ($v['course_type'] == 'spark') {
                $title = Db::name('learning')
                    ->where('id', '=', $v['courseid'])
                    ->value('title');
                $v['seminar'] = $title;
                $v['course_type_name'] = 'SPARK';

            } elseif ($v['course_type'] == 'zhibo') {
                $course_info = Db::name('live')->where('id', '=', $v['courseid'])->field('title')->find();
                $v['seminar'] = $course_info['title'];
                $v['seminar_topic'] = '';
                $v['course_type_name'] = '直播课';
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    //选课
    public function xuanke(Request $request)
    {
        $category_id = $request->get('category_id');

        if (!$category_id) {
            return $this->outputAjax('参数不足！');
        }

        $s = Db::name('elearning_course')
            ->where('category_id', '=', $category_id)
            ->where('type', '=', 'spark')
            ->column('courseid');

        $oneflex = Db::name('learning')
            ->where('status', '=', 1)
            ->where('range', '=', 1)
            ->field('id as value, title')
            ->select();

        View::assign('spark_str', json_encode($s));
        View::assign('spark', json_encode($oneflex));


        //轻学堂
        $qxt = Db::name('qxt_courses')
            ->where('status', '=', 1)
            ->where('using', '=', 1)
            ->field('id as value, courseTitle as title')
            ->select();

        $s4 = Db::name('elearning_course')
            ->where('category_id', '=', $category_id)
            ->where('type', '=', 'qxt')
            ->column('courseid');
        View::assign('qxt_str',json_encode($s4));
        View::assign('qxt', json_encode($qxt));
        

        //直播
        $zhibo = Db::name('live')
            ->where('status', '=', 1)
            ->where('open', '=', 2)
            ->where('end', '<', time())
            ->order('start', 'desc')
            ->field('id as value, title')
            ->select();

        $s4 = Db::name('elearning_course')
            ->where('category_id', '=', $category_id)
            ->where('type', '=', 'zhibo')
            ->column('courseid');
        View::assign('zhibo_str',json_encode($s4));
        View::assign('zhibo', json_encode($zhibo));

        View::assign('category_id', $category_id);
        return View::fetch();
    }

    // 保存课程
    public function saveCourse(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post['category_id']) || empty($post['type'])) {
            return $this->outputAjax('参数不足！');
        }

        try {
            //找出所有旧的，成功之后删除
            $old = Db::name('elearning_course')
                ->where('category_id', '=', $post['category_id'])
                ->where('type', '=', $post['type'])
                ->column('courseid');

            $temp = [];
            $temp['category_id'] = $post['category_id'];
            $temp['type'] = $post['type'];
            if (empty($post['courseid'])) {
                $arr = [];
            } else {
                $arr = $post['courseid'];
            }

            $arr1 = array_diff($old,$arr);
            $arr2 = array_diff($arr,$old);
            if (!empty($arr2)) {
                foreach ($arr2 as $key => $value) {
                    if ($value) {
                        $temp['courseid'] = $value;
                        $temp['add_time'] = time();
                        Db::name('elearning_course')->insert($temp);
                    }
                }
            }

            //+删除旧课程
            if (!empty($arr1)) {
                Db::name('elearning_course')
                    ->where('category_id', '=', $post['category_id'])
                    ->where('courseid', 'in', $arr1)
                    ->delete();
            }
            return $this->outputAjax('选课成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }



    //+课程排序
    public function setCourseSort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }
        Db::startTrans();
        try {
            $res = Db::name('elearning_course')->where('id', '=', $post['id'])->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }

            $rows = Db::name('elearning_course')
                ->where('category_id', '=', $post['category_id'])
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort', 'asc')
                ->select();
            if (!Db::name('elearning_course')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('elearning_course')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }

                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }
}